<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
    <a-form>
      <a-form-item :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
        <a-button :loading="loading" @click="addNew" type="primary">
          新增
        </a-button>
      </a-form-item>
      <a-form-item>
        <a-table
          rowKey="id"
          :defaultExpandAllRows="true"
          :columns="columns"
          :data-source="data"
        >
          <template #headerCell="{}"> </template>

          <template #bodyCell="{ column, record }">
            <template v-if="column.key == 'actions'">
              <a-button type="link" @click="handleEdit(record)">修改 </a-button>
              <a-button type="link" @click="handleDel(record)">删除 </a-button>
            </template>
          </template>
        </a-table>
      </a-form-item>
    </a-form>
    <AddModal ref="addModal" @refreshTable="loadDepts" />
    <EditModal ref="editModal" @refreshTable="loadDepts" />
  </a-card>
</template>
<script lang="ts">
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { defineComponent, reactive, ref, UnwrapRef, onMounted } from "vue";
import {
  UserOutlined,
  LockOutlined,
  QrcodeOutlined,
} from "@ant-design/icons-vue";
import ResultEnum from "@/config/ResultEnum";
import { getDepts, cols, delDept } from "./index";
import { treeTransToArray } from "@/utils/common";
import { Modal } from "ant-design-vue";
import AddModal from "./addModal/index.vue";
import EditModal from "./editModal/index.vue";

export default defineComponent({
  components: {
    AddModal,
    EditModal,
  },
  setup() {
    const addModal = ref();
    const editModal = ref();
    const router = useRouter();
    const loading = ref(false);
    const columns = ref(cols);
    const data = ref([]);

    const addNew = () => {
      addModal.value.display();
    };

    onMounted(() => {
      loadDepts();
    });

    const loadDepts = () => {
      loading.value = true;
      getDepts()
        .then((res: any) => {
          loading.value = false;
          data.value = res;
        })
        .catch((res: string) => {
          loading.value = false;
          message.error(res);
        });
    };

    const handleEdit = (record: any) => {
      editModal.value.display(record.id);
    };

    const handleDel = (record: any) => {
      Modal.confirm({
        title: "提示?",
        content: "确定删除【" + record.deptName + "】?",
        onOk() {
          delDept(record.id)
            .then((res: any) => {
              loadDepts();
            })
            .catch((res: string) => {
              message.error(res);
            });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    };

    return {
      loading,
      addNew,
      columns,
      data,
      handleEdit,
      handleDel,
      loadDepts,
      addModal,
      editModal,
    };
  },
});
</script>
